import { create } from 'zustand'
import { persist } from 'zustand/middleware'

interface User {
  id: number
  username: string
  email: string
  role?: string
  name?: string
  phone?: string
  address?: string
}

interface AuthState {
  user: User | null
  token: string | null
  isAuthenticated: boolean
  login: (data: { user: User; token: string }) => void
  logout: () => void
  updateProfile: (data: { 
    username?: string
    email?: string
    name?: string
    phone?: string
    address?: string 
  }) => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      login: ({ user, token }) =>
        set({
          user,
          token,
          isAuthenticated: true,
        }),
      logout: () =>
        set({
          user: null,
          token: null,
          isAuthenticated: false,
        }),
      updateProfile: (data) =>
        set((state) => ({
          user: state.user ? { ...state.user, ...data } : null,
        })),
    }),
    {
      name: 'auth-storage',
      storage: {
        getItem: (name) => {
          try {
            if (typeof window === 'undefined') return null
            const fromCookie = document.cookie
              .split('; ')
              .find(row => row.startsWith(name))
              ?.split('=')[1]
            return fromCookie ? decodeURIComponent(fromCookie) : null
          } catch (error) {
            console.error('Error reading auth data:', error)
            return null
          }
        },
        setItem: (name, value) => {
          try {
            if (typeof window === 'undefined') return
            // 确保值是字符串
            const stringValue = typeof value === 'string' ? value : JSON.stringify(value)
            const encodedValue = encodeURIComponent(stringValue)
            document.cookie = `${name}=${encodedValue}; path=/; max-age=2592000; SameSite=Lax`
          } catch (error) {
            console.error('Error setting auth data:', error)
          }
        },
        removeItem: (name) => {
          if (typeof window === 'undefined') return
          document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Lax`
        },
      },
    }
  )
) 